const mysql = require('mysql2/promise');
require('dotenv').config();

// 添加调试信息
console.log('🔧 数据库配置调试:');
console.log('DB_HOST:', process.env.DB_HOST || 'localhost');
console.log('DB_USER:', process.env.DB_USER || 'root');
console.log('DB_PASSWORD:', process.env.DB_PASSWORD ? '***' : '空');
console.log('DB_NAME:', process.env.DB_NAME || 'campus_parcel_pickup_service');

const pool = mysql.createPool({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD,
    database: 'campus_parcel_pickup_service',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 修改测试连接，显示更多信息
async function testConnection() {
    try {
        const connection = await pool.getConnection();
        console.log('✅ 数据库连接成功');

        // 测试当前用户权限
        const [rows] = await connection.execute('SELECT CURRENT_USER() as user, DATABASE() as db');
        console.log('🔑 当前数据库用户:', rows[0].user);
        console.log('🗄️ 当前数据库:', rows[0].db);

        connection.release();
    } catch (error) {
        console.error('❌ 数据库连接失败:', error.message);
    }
}

testConnection();

module.exports = pool;